import 'dart:async';
import 'dart:convert';
import 'dart:isolate';

import 'package:flutter/material.dart';
//as 为了解决方法名冲突的问题！通过 重命名.方法名 调用
import 'package:http/http.dart' as http; //重命名为http
//hide 隐藏某个不要导入的方法
import 'package:my_app/003--项目实战-项目搭建/wechat_demo03/pages/const.dart';

class ChatPage extends StatefulWidget {
  @override
  _ChatPageState createState() => _ChatPageState();
}

int count = 0;

class _ChatPageState extends State<ChatPage> {
  Widget _buildPopupMenuItem(String imageAss, String title) {
    return Row(
      children: <Widget>[
        Image(
          image: AssetImage(imageAss),
          width: 20,
        ),
        Container(
          width: 20,
        ),
        Text(
          title,
          // style: TextStyle(color: Colors.white),
        ),
      ],
    );
  }

  bool _cancleConnect = false;

  List<Chat> _datas = [];
  @override
  void initState() {
    super.initState();
    print('Chat的init来了!');
    getDatas()
        .then((List<Chat> datas) {//超时了数据还会来
          print('数据来了!');
          if (!_cancleConnect) {
            print('更新数据');
            setState(() {
              _datas = datas;
            });
          }
        })
        .catchError((e) {
          print('错误$e');
        })
        .whenComplete(() {
          print('完毕!');
        })
        .timeout(Duration(seconds: 6))
        .catchError((timeout) {
          _cancleConnect = true;
          print('超时输出:$timeout');
        });
  }

  Timer _timer = Timer.periodic(Duration(seconds: 1), (timer) {
    print(count);
    print(Isolate.current.debugName);
    count++;
    if(count>100){
      timer.cancel();
    }
  });

  @override
  void dispose(){
    print('dispose');
    _timer.cancel();
    super.dispose();
  }

  Future<List<Chat>> getDatas() async {
    //不再是取消连接了!
    _cancleConnect = false;
    final response = await http
        .get('http://rap2api.taobao.org/app/mock/277850/api/chat/list');
    if (response.statusCode == 200) {
      //获取相应数据,并转成Map类型!
      final responseBody = json.decode(response.body);
      // print('response.body:'+response.body);
      // print('responseBody:'+responseBody);
      // print('responseBody[chat_list]:'+responseBody['chat_list']);
      //转模型数组 map中遍历的结果需要返回出去
      List<Chat> chatList = responseBody['chat_list'].map<Chat>((item) {//遍历
        // print('item:'+item);
        return Chat.fromJson(item);
      }).toList();
      // print(chatList);
      return chatList;
    } else {
      throw Exception('statusCode:${response.statusCode}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('薪信'),
        backgroundColor: WeChatThemeColor,
        actions: <Widget>[
          Container(
            margin: EdgeInsets.only(right: 10),
            child: PopupMenuButton(
              offset: Offset(0, 60.0),
              color: WeChatThemeColor,
              child: Image(
                image: AssetImage('images/圆加.png'),
                width: 25,
              ),
              itemBuilder: (BuildContext context) {
                return <PopupMenuItem<String>>[
                  PopupMenuItem(
                      child: _buildPopupMenuItem('images/发起群聊.png', '发起群聊')
                  ),
                  PopupMenuItem(
                      child:_buildPopupMenuItem('images/添加朋友.png', '添加朋友')
                  ),
                  PopupMenuItem(
                      child: _buildPopupMenuItem('images/扫一扫1.png', '扫一扫')),
                  PopupMenuItem(
                      child: _buildPopupMenuItem('images/收付款.png', '收付款')),
                ];
              },
            ),
          ) //右上角按钮
        ],
      ),
      body: Container(
        child: _datas.length == 0
            ? Center(
                child: Text("Loading..."),
              )
            : ListView.builder(
                itemCount: _datas.length,
                itemBuilder: (BuildContext context, int index) {
                  // print(_datas[index].name);
                  // print(_datas[index].message);
                  // print(_datas[index].imageUrl);
                  return ListTile(
                      title: Text(_datas[index].name),
                      subtitle: Container(
                        alignment: Alignment.bottomCenter,
                        padding: EdgeInsets.only(right: 10),
                        height: 25,
                        child: Text(
                          _datas[index].message,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      leading: Container(
                        width: 44,
                        height: 44,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(6.0),
                            image: DecorationImage(
                                image: NetworkImage(_datas[index].imageUrl))),
                      ));
                },
              ),
      ),
    );
  }
}
/*
  FutureBuilder(
    future: getDatas(),
    builder: (BuildContext context, AsyncSnapshot snapshot) {
    //正在加载
    if (snapshot.connectionState == ConnectionState.waiting) {
    return Center(
    child: Text('Loading...'),
    );
    }
    //加载完毕
    return ListView(
    children: snapshot.data.map<Widget>((item) {
    return ListTile(
    title: Text(item.name),
    subtitle: Container(
    alignment: Alignment.bottomCenter,
    padding: EdgeInsets.only(right: 10),
    height: 25,
    child: Text(
    item.message,
    overflow: TextOverflow.ellipsis,
    ),
    ),
    leading: Container(
    width: 44,
    height: 44,
    decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(6.0),
    image: DecorationImage(
    image: NetworkImage(item.imageUrl))),
    ));
    }).toList(),
    );
    },
    )),
 * */

class Chat {
  final String name;
  final String message;
  final String imageUrl;

  const Chat({this.name, this.message, this.imageUrl});//必须创建新对象

  factory Chat.fromJson(Map json) {//工厂构造函数：返回任何对象，已有的对象（单例），null，新建的
    // print('json:');
    // print(json);
    return Chat(
      name: json['name'],
      message: json['message'],
      imageUrl: json['imageUrl'],
    );
  }
}

//关于Map和Json
/*
*
//    final chat = {
//      'name': '张三',
//      'message': '吃了吗?',
//    };
    //Map转Json
//    final chatJson = json.encode(chat);
//    print(chatJson);

    //Json转Map
//    final newChat = json.decode(chatJson);
//    print(newChat['name']);
//    print(newChat['message']);
//    print(newChat is Map);
* */
